package org.example.judge_common.interceptors;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.example.judge_common.annotation.AuthAnnotation;
import org.example.judge_common.entity.ResponseResult;
import org.example.judge_common.hander.RetrunMsgException;
import org.example.judge_common.util.MyUtils;
import org.example.judge_pojo.Auth;
import org.example.judge_pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
@Data
public class LoginInterceptor implements HandlerInterceptor {



    @Autowired
    private RedisTemplate redisTemplate;
    private User getToken(HttpServletRequest request){
        //获取头信息中的token信息
        String token1 = request.getHeader("token");
        if(MyUtils.isEmpty(token1))return null;
        Object o = redisTemplate.opsForValue().get(token1);
        if(o==null)return null;
        return JSON.parseObject(((String) o),User.class);
    }

    /**
     * 判断是否有访问权限
     */
    private boolean isPermissionAPI(List<Auth> auths, HandlerMethod handler){

        //获取请求方法上的AuthAnnotation注解
        AuthAnnotation authAnnotation = handler.getMethodAnnotation(AuthAnnotation.class);




        String[] authCode = authAnnotation.value();;  //记录请求的方法上的code值


        if(auths==null)return false; //该用户无权限

        for (Auth auth : auths) {
            for (String code : authCode) {
                if(Auth.isAuth(auth.getCode(),code)){  //进行权限对比
                    return true;
                }
            }

        }

        return false;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取头信息中的token信息
        String token1 = request.getHeader("token");
//        System.out.println(token1+","+request.getLocalAddr()+","+InetAddress.getLocalHost().getHostAddress());
        if(Auth.ROOT.equals(token1)) {
            User user = new User();
            user.setId("1");
            user.setUsername("系统管理员");
            return true;  //api内部访问}
        }

//        System.out.println(request);
        HandlerMethod handlerMethod = null;
        try{
            handlerMethod = (HandlerMethod) handler;
        }catch (ClassCastException e){
            log.warn("未知错误：",e.getMessage());
            return true;
        }
//        System.out.println(handlerMethod);
        AuthAnnotation authAnnotation = handlerMethod.getMethodAnnotation(AuthAnnotation.class);
        //不需要权限直接放行




        User user = this.getToken(request);
//        System.out.println(user);
        request.setAttribute("loginUser",user);
        if(authAnnotation==null||!authAnnotation.exist())return true;  //无注解不需要登录
        if(user==null)throw new RetrunMsgException("未登录", ResponseResult.unLogin());

        //权限判定
        if (!this.isPermissionAPI(user.getAuths(), handlerMethod)) {
            throw new RetrunMsgException("权限不足",ResponseResult.unAuditor());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //数据过滤
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

